var app = angular.module("audittest", []);

var g_systemtitle = "用友审计考试系统";

window.copyrighttext = "© 2017 北京用友审计软件有限公司. Licensed under MIT license.";

// 全局设置

var testitemtype = ["单选题", "多选题", "判断题", "问答题", "名词解释", "编程题", "主观题", "填空题"];

var personsexs = [{
    "label": "男",
    "value": "M"
}, {
    "label": "女",
    "value": "F"
}];

var difficulties = [{
    "label": "难",
    "value": 3
}, {
    "label": "中",
    "value": 2
}, {
    "label": "易",
    "value": 1
}];

var arrayToReverseMap = function (arrs, value, key) {
    var result = {};
    for (var i = 0, j = arrs.length; i < j; i++) {
        var arr = arrs[i];
        var k = arr[key];
        var v = arr[value];
        result[v] = k;
    }
    return result;
};

var toporganize = [{
    "title": "用友审计软件有限公司",
    "type": "folder",
    "ext": "",
    "subs": []
}];

var _confirm = function (msg, confn, canfn) {
    var title = "任职资格考试系统";
    var confirmHtml = "<div class='am-modal am-modal-confirm' tabindex='-1' id='ALERT_ID'>"
        + "<div class='am-modal-dialog'>"
        + "  <div class='am-modal-hd'>ALERT_TITLE</div>"
        + "  <div class='am-modal-bd'>"
        + "    ALERT_MSG"
        + "  </div>"
        + "  <div class='am-modal-footer'>"
        + "    <span class='am-modal-btn' data-am-modal-cancel>取消</span>"
        + "    <span class='am-modal-btn' data-am-modal-confirm>确定</span>"
        + "  </div></div></div>";
    var confirm_id = "al_id_" + Math.round(Math.random(10) * 100000);
    var nahtml = confirmHtml.replace(/ALERT_TITLE/, title).replace(/ALERT_MSG/,
        msg).replace(/ALERT_ID/, confirm_id);
    $("body").append($(nahtml));
    $("#" + confirm_id).on("closed.modal.amui", function () {
        $("#" + confirm_id).remove();
    });
    $("#" + confirm_id).modal({
        closeViaDimmer: 0,
        relatedTarget: this,
        onConfirm: function (options) {
            if (confn)
                confn();
        },
        onCancel: function () {
            if (canfn)
                canfn();
        }
    });
};

var _alert = function (msg) {
    var title = "任职资格考试系统";
    var alertHtml = "<div class='am-modal am-modal-alert' tabindex='-1' id='ALERT_ID'>"
        + "<div class='am-modal-dialog'>"
        + "  <div class='am-modal-hd'>ALERT_TITLE</div>"
        + "  <div class='am-modal-bd'>"
        + "    ALERT_MSG"
        + "  </div>"
        + "  <div class='am-modal-footer'>"
        + "    <span class='am-modal-btn'>确定</span>"
        + "  </div></div></div>";
    var alert_id = "al_id_" + Math.round(Math.random(10) * 100000);
    var nahtml = alertHtml.replace(/ALERT_TITLE/, title).replace(/ALERT_MSG/,
        msg).replace(/ALERT_ID/, alert_id);
    $("body").append($(nahtml));
    $("#" + alert_id).on("closed.modal.amui", function () {
        $("#" + alert_id).remove();
    });
    $("#" + alert_id).modal({
        closeViaDimmer: 0,
    });
};

var treeSelectedEvent = function (id, fn) {
    $("#" + id).on('selected.tree.amui', function (event, data) {
        fn(event, data);
    });
};

window.logout = function () {
    _confirm("您真的要注销吗？", function () {
        location.href = "./logout";
    });
};

app.config([
    "$httpProvider",
    function ($httpProvider) {
        $httpProvider.interceptors.push(function () {
            return {
                'request': function (config) {
                    if (config.method == "GET") {
                        var url = config.url;
                        if (/.*?\?.*/.test(url)) {
                            url = url + "&t=" + new Date().getTime();
                        } else {
                            url = url + "?t=" + new Date().getTime();
                        }
                        config.url = url;
                    } else {
                        if (config.method == "POST") {
                            if (__w && __w.ep) {
                                var data = config.data;
                                var plaintext = JSON.stringify(data);
                                var aesUtil = new AesUtil(ep.d, ep.c);
                                var ciphertext = aesUtil.encrypt(ep.k,
                                    ep.l, ep.m, plaintext);
                                config.data = ciphertext;
                            }
                        }
                    }
                    return config;
                }
            };
        });
    }]);

// angular 全局服务
app.filter("sexfilter", function () {
    return function (ov) {
        if (ov == "M")
            return "男";
        else
            return "女";
    };
});

app.service("basicinfo", ["$http", "$q", function ($http, $q) {
    this.getorgs = this.getorganizes = function () {
        var def = $q.defer();
        $http.get("./getorganizes").success(function (data) {
            def.resolve(data);
        }).error(function () {
            def.reject("请求机构列表数据错误");
        });
        return def.promise;
    };

    this.getlevels = function () {
        var def = $q.defer();
        $http.get("./getlevellist").success(function (data) {
            def.resolve(data);
        }).error(function () {
            def.reject("请求职级列表数据错误");
        });
        return def.promise;
    };

    this.getcates = function () {
        var def = $q.defer();
        $http.get("./getcatelist").success(function (data) {
            def.resolve(data);
        }).error(function () {
            def.reject("请分类列表数据错误");
        });
        return def.promise;
    };

    this.getseqs = function () {
        var def = $q.defer();
        $http.get("./getseqlist").success(function (data) {
            def.resolve(data);
        }).error(function () {
            def.reject("请序列列表数据错误");
        });
        return def.promise;
    };

    this.getmyinfo = function () {
        var def = $q.defer();
        $http.get("./getuserinfo").success(function (data) {
            def.resolve(data);
        }).error(function () {
            def.reject("获取权限信息失败");
        });
        return def.promise;
    };
}]);

app.service("dialog", [function () {
    this.alert = _alert;
    this.confirm = _confirm;
}]);

// 登录
app
    .controller(
        "sys-login",
        [
            "$scope",
            "$http",
            "dialog",
            "$compile",
            function ($scope, $http, dialog, $compile) {
                $scope.systemtitle = g_systemtitle;
                $scope.user = {
                    "email": "",
                    "password": ""
                };

                $scope.refreshImg = function () {
                    var url = "./jym.jpg?t=" + Math.random();
                    var htmlstr = '<input type="text" style="float: left; width: 100px; margin-right: 10px;" data-ng-model="user.jym" id="jyminput" style="width: 20%" placeholder="验证码"/> <img src="'
                        + url
                        + '" data-ng-click="refreshImg()" id="jym" style="cursor: pointer;" />'
                        + '<button style="float: right; margin-right: 10px; width: 100px;height: 37px;" type="button"'
                        + ' class="am-btn am-btn-primary am-btn-lg am-fl"'
                        + ' data-ng-click="login()">登 录</button>';
                    htmlstr = $compile(htmlstr)($scope);
                    $("#imgdiv").html(htmlstr);
                };

                $scope.login = function () {
                    if ($scope.user.email == ""
                        || $scope.user.password == "") {
                        return dialog.alert("请将信息输入完整！");
                    }
                    if (!$scope.user.email) {
                        $scope.user.email = $("#email").val();
                    }
                    if (!$scope.user.password) {
                        $scope.user.password = $("#passwd").val();
                    }
                    $http.post("./login", $scope.user).success(
                        function (data) {
                            if (data.status == "ok") {
                                location.href = "./index";
                            } else {
                                dialog.alert(data.msg);
                                $scope.user.password = "";
                                $scope.refreshImg();
                            }
                        }).error(function () {
                        alert("登录操作失败");
                    });
                };

                $("#email").bind("keypress", function (event) {
                    if (event.keyCode == "13") {
                        $("#passwd").focus();
                    }
                });

                $("#passwd").bind('keypress', function (event) {
                    if (event.keyCode == "13") {
                        $scope.login();
                    }
                });

            }]);

// 管理系统首页
app.controller("admin", ["$scope", "$http", "basicinfo",
    function ($scope, $http, basicinfo) {
        $scope.go2nav = function () {
            location.href = "../index";
        };
    }]);

// 序列管理
app.controller("admin-seq", [
    "$scope",
    "$http",
    "basicinfo",
    "dialog",
    function ($scope, $http, basicinfo, dialog) {
        $scope.items = [];
        $scope.currentItem = {};
        var init = function () {
            basicinfo.getseqs().then(function (data) {
                $scope.items = data;
            });
        };

        $scope.edit = function (item) {
            $scope.currentItem = item;
            $("#doc-modal-1").modal('open');
        };

        $scope.add = function () {
            $scope.currentItem = {};
            $("#doc-modal-1").modal('open');
        };

        $scope.deleteItem = function (item) {
            dialog.confirm("您真的要删除序列 " + item.seqname + " 吗?", function () {
                $http.get("./deleteseq?seqbh=" + encodeURI(item.seqbh))
                    .success(function (data) {
                        if (data.status == "ok")
                            location.reload();
                    }).error(function () {
                    alert("序列删除失败");
                });
            });
        };

        $scope.postData = function () {
            $http.post("./postseqdata", $scope.currentItem).success(
                function (data) {
                    if (data.status == "ok")
                        location.reload();
                }).error(function () {
                alert("请求分类列表数据错误");
            });
            $("#doc-modal-1").modal('close');
        };
        init();
    }]);

// 分类管理
app.controller("admin-cate", [
    "$scope",
    "$http",
    "basicinfo",
    "dialog",
    function ($scope, $http, basicinfo, dialog) {
        $scope.items = [];
        $scope.currentItem = {};
        var init = function () {
            basicinfo.getcates().then(function (data) {
                $scope.items = data;
            });
        };

        $scope.edit = function (item) {
            $scope.currentItem = item;
            $("#doc-modal-1").modal('open');
        };

        $scope.add = function () {
            $scope.currentItem = {};
            $("#doc-modal-1").modal('open');
        };

        $scope.deleteItem = function (item) {
            dialog.confirm("您真的要删除分类 " + item.catename + " 吗?", function () {
                $http.get("./deletecate?catebh=" + encodeURI(item.catebh))
                    .success(function (data) {
                        if (data.status == "ok")
                            location.reload();
                    }).error(function () {
                    alert("分类删除失败");
                });
            });
        };

        $scope.postData = function () {
            $http.post("./postcatedata", $scope.currentItem).success(
                function (data) {
                    if (data.status == "ok")
                        location.reload();
                }).error(function () {
                alert("请求分类列表数据错误");
            });
            $("#doc-modal-1").modal('close');
        };

        init();
    }]);

// 职级管理
app.controller("admin-level", [
    "$scope",
    "$http",
    "basicinfo",
    "dialog",
    function ($scope, $http, basicinfo, dialog) {
        $scope.items = [];
        $scope.currentItem = {};
        var init = function () {
            basicinfo.getlevels().then(function (data) {
                $scope.items = data;
            });
        };

        $scope.edit = function (item) {
            $scope.currentItem = item;
            $("#doc-modal-1").modal('open');
        };

        $scope.add = function () {
            $scope.currentItem = {};
            $("#doc-modal-1").modal('open');
        };

        $scope.deleteItem = function (item) {
            dialog.confirm("您真的要删除职级 " + item.levelname + " 吗?",
                function () {
                    $http.get(
                        "./deletelevel?levelbh="
                        + encodeURI(item.levelbh)).success(
                        function (data) {
                            if (data.status == "ok")
                                location.reload();
                        }).error(function () {
                        alert("序列删除失败");
                    });
                });
        };

        $scope.postData = function () {
            $http.post("./postleveldata", $scope.currentItem).success(
                function (data) {
                    if (data.status == "ok")
                        location.reload();
                }).error(function () {
                alert("请求分类列表数据错误");
            });
            $("#doc-modal-1").modal('close');
        };

        init();
    }]);

// 机构管理
app.controller("admin-org", [
    "$scope",
    "$http",
    "basicinfo",
    "dialog",
    function ($scope, $http, basicinfo, dialog) {
        $scope.currentItem = {};
        $scope.data = toporganize;
        var snapshot = {};

        var buildTreeData = function (data, currentNode) {
            var attr = currentNode.ext;
            snapshot[attr || "--"] = currentNode;
            if (attr == "") { // root
                for (var i = 0, j = data.length; i < j; i++) {
                    var item = data[i];
                    var a = item.parentbh;
                    if (!a) {
                        var arr = currentNode.subs;
                        if (!arr) {
                            arr = [];
                            currentNode.subs = arr;
                        }
                        var a = {};
                        a.title = item.orgname;
                        a.ext = item.orgbh;
                        a.type = "item";
                        arr.push(a);
                        buildTreeData(data, a);
                    }
                }
            } else {
                for (var i = 0, j = data.length; i < j; i++) {
                    var item = data[i];
                    var a = item.parentbh;
                    if (a == currentNode.ext) {
                        var arr = currentNode.subs;
                        if (!arr) {
                            arr = [];
                            currentNode.subs = arr;
                        }
                        var a = {};
                        a.title = item.orgname;
                        a.ext = item.orgbh;
                        a.type = "item";
                        arr.push(a);
                        buildTreeData(data, a);
                    }
                }
            }
            if (currentNode.subs && currentNode.subs.length > 0) {
                currentNode.type = "folder";
            } else {
                currentNode.type = "item";
            }
        };

        var buildTree = function () {
            $('#firstTree').tree({
                dataSource: function (options, callback) {
                    try {
                        callback({
                            data: options.subs || $scope.data
                        });
                    } catch (e) {

                    }
                },
                multiSelect: false,
                cacheItems: false,
                folderSelect: true
            }).tree('discloseAll');
        };

        var init = function () {
            basicinfo.getorgs().then(function (data) {
                buildTreeData(data, $scope.data[0]);
                buildTree();
            });
        };

        $scope.add = function () {
            var parent = $scope.currentItem;
            $scope.currentItem = {};
            $scope.currentItem.parent = parent.ext;
        };

        $scope.deleteItem = function () {
            dialog.confirm("您真的要删除当前机构吗？", function () {
                $http.get(
                    "./deleteorg?orgbh="
                    + encodeURI($scope.currentItem.ext))
                    .success(function (data) {
                        if (data.status == "ok")
                            location.reload();
                        else
                            dialog.alert("机构删除失败");
                    }).error(function () {
                    alert("机构删除失败");
                });
            });
        };

        $scope.postData = function () {
            var item = {};
            item.orgbh = $scope.currentItem.ext;
            item.parentbh = $scope.currentItem.parent;
            if (item.parentbh == "") {
                delete item.parentbh;
            }
            item.orgname = $scope.currentItem.title;
            $http.post("./postorgdata", item).success(function (data) {
                if (data.status == "ok")
                    location.reload();
            }).error(function () {
                alert("更新机构数据错误");
            });
        };

        treeSelectedEvent("firstTree", function (event, data) {
            // do something with data: { selected: [array], target: [object]
            // }
            if (data.target) {
                var attr = data.target.ext || "--";
                $scope.currentItem = snapshot[attr];
                if (!$scope.$$phase) {
                    $scope.$apply();
                }
            }
        });
        init();
    }]);

// 人员管理

app.filter('checkStatus', function () {
    return function (status) {
        return status == 1 ? "有效" : "无效";
    }
})

app.filter('showStatus', function () {
    return function (status) {
        return status == 1 ? "am-btn am-btn-success" : "am-btn am-btn-default";
    }
})

app.controller("admin-person", [
    "$scope",
    "$http",
    "$q",
    "basicinfo",
    "dialog",
    function ($scope, $http, $q, basicinfo, dialog) {
        $scope.currentItem = {};

        $scope.data = toporganize;

        $scope.sexs = personsexs;

        $scope.orgs = [];
        $scope.orgPathMaps = [];

        var snapshot = {};
        var buildTreeData = function (data, currentNode, orgtitle) {
            var attr = currentNode.ext;
            if (!orgtitle) {
                currentNode.path = currentNode.title;
            } else {
                currentNode.path = orgtitle + "/" + currentNode.title;
            }
            $scope.orgs.push(currentNode);
            $scope.orgPathMaps[attr] = currentNode.path;
            snapshot[attr || "--"] = currentNode;
            if (attr == "") { // root
                for (var i = 0, j = data.length; i < j; i++) {
                    var item = data[i];
                    var a = item.parentbh;
                    if (!a) {
                        var arr = currentNode.subs;
                        if (!arr) {
                            arr = [];
                            currentNode.subs = arr;
                        }
                        var a = {};
                        a.title = item.orgname;
                        a.ext = item.orgbh;
                        a.type = "item";
                        arr.push(a);
                        buildTreeData(data, a, currentNode.path);
                    }
                }
            } else {
                for (var i = 0, j = data.length; i < j; i++) {
                    var item = data[i];
                    var a = item.parentbh;
                    if (a == currentNode.ext) {
                        var arr = currentNode.subs;
                        if (!arr) {
                            arr = [];
                            currentNode.subs = arr;
                        }
                        var a = {};
                        a.title = item.orgname;
                        a.ext = item.orgbh;
                        a.type = "item";
                        arr.push(a);
                        buildTreeData(data, a, currentNode.path);
                    }
                }
            }
            if (currentNode.subs && currentNode.subs.length > 0) {
                currentNode.type = "folder";
            } else {
                currentNode.type = "item";
            }
        };

        var buildTree = function () {
            $('#firstTree').tree({
                dataSource: function (options, callback) {
                    try {
                        callback({
                            data: options.subs || $scope.data
                        });
                    } catch (e) {

                    }
                },
                multiSelect: false,
                cacheItems: false,
                folderSelect: true
            }).tree('discloseAll');
        };

        var getorganizes = function () {
            var def = $q.defer();
            basicinfo.getorgs().then(function (data) {
                buildTreeData(data, $scope.data[0]);
                buildTree();
                def.resolve();
            }, function () {
                def.reject("请求机构列表数据错误");
            });
            return def.promise;
        };

        var getlevels = function () {
            var def = $q.defer();
            basicinfo.getlevels().then(function (data) {
                $scope.levels = data;
                def.resolve();
            }, function () {
                def.reject("请求职级列表数据错误");
            });
            return def.promise;
        };

        var getcates = function () {
            var def = $q.defer();
            basicinfo.getcates().then(function (data) {
                $scope.cates = data;
                def.resolve();
            }, function () {
                def.reject("请分类列表数据错误");
            });
            return def.promise;
        };

        var getseqs = function () {
            var def = $q.defer();
            basicinfo.getseqs().then(function (data) {
                $scope.seqs = data;
                def.resolve();
            }, function () {
                def.reject("请序列列表数据错误");
            });
            return def.promise;
        };

        var init = function () {
            getseqs().then(getcates).then(getlevels).then(getorganizes);
        };

        $scope.add = function () {
            $scope.currentItem = {};
            if ($scope.currentOrg != null) {
                $scope.currentItem.userdep = $scope.currentOrg.ext;
            }
            $("#doc-modal-1").modal('open');
        };

        $scope.edit = function (item) {
            $scope.currentItem = item;
            $("#doc-modal-1").modal('open');
        };

        $scope.deleteItem = function (item) {
            dialog.confirm("您真的要删除 " + item.username + " 吗？", function () {
                $http
                    .get(
                        "./deleteperson?userbh="
                        + encodeURI(item.userbh)).success(
                    function (data) {
                        if (data.status == "ok")
                            location.reload();
                        else
                            dialog.alert("人员删除失败");
                    }).error(function () {
                    alert("人员删除失败");
                });
            });
        };

        $scope.postData = function () {
            $http.post("./postpersondata", $scope.currentItem).success(
                function (data) {
                    if (data.status == "ok") {
                        // location.reload();
                        alert("人员编辑成功！");
                        $("#doc-modal-1").modal('close');
                    }
                }).error(function () {
                alert("更新人员数据错误");
            });
        };

        $scope.resetPass = function (item) {
            dialog.confirm("您真的要重置 " + item.username + " 的密码吗？",
                function () {
                    $http.get(
                        "./resetpass?userbh="
                        + encodeURI(item.userbh)).success(
                        function (data) {
                            if (data.status == "ok") {
                                dialog.alert("用户重置密码操作成功");
                            } else {
                                dialog.alert("用户重置密码操作失败");
                            }
                        }).error(function () {
                        alert("用户重置密码操作失败");
                    });
                });
        };

        $scope.editStatus = function ($event, item) {
            $http.get(
                "./editStatus?userbh=" + encodeURI(item.userbh)
                + "&enabled="
                + encodeURI(item.enabled == 1 ? 0 : 1))
                .success(function (data) {
                    if (data.status == "ok") {
                        item.enabled = item.enabled == 1 ? 0 : 1;
                    } else {
                        dialog.alert("状态修改失败");
                    }
                }).error(function () {
                alert("状态修改失败");
            });
        };

        treeSelectedEvent("firstTree", function (event, data) {
            if (data.target) {
                var attr = data.target.ext || "--";
                $scope.currentOrg = snapshot[attr];
                var url = "./getpersonlist";
                if (attr != "--") {
                    url += "?orgbh=" + encodeURI(attr);
                }
                $http.get(url).success(function (data) {
                    $scope.persons = data;
                }).error(function () {
                    alert("获取用户数据失败");
                });
            }
        });

        var submitFileForm = function (callback) {
            var submitForm = document.getElementById("submitForm");
            var iframe = document.createElement("iframe");
            iframe.width = 0;
            iframe.height = 0;
            iframe.border = 0;
            iframe.name = "form-iframe";
            iframe.id = "form-iframe";
            iframe.setAttribute("style", "width:0;height:0;border:none");
            // 放到document
            submitForm.appendChild(iframe);
            submitForm.action = "./batchAdd";
            submitForm.target = "form-iframe";
            iframe.onload = function () {
                // 获取iframe的内容，即服务返回的数据
                var responseData = this.contentDocument.body.textContent
                    || this.contentWindow.document.body.textContent;
                try {
                    var resultJson = JSON.parse(responseData);
                    if (resultJson.msg)
                        alert(resultJson.msg);
                    init();
                } catch (e) {

                } finally {
                    // 删掉iframe
                    setTimeout(
                        function () {
                            var _frame = document
                                .getElementById("form-iframe");
                            _frame.parentNode.removeChild(_frame);
                        }, 200);
                }
            }
            submitForm.submit();
        };

        $(function () {
            $('#doc-prompt-toggle').on('click', function () {
                $('#my-prompt').modal({
                    relatedTarget: this,
                    closeOnConfirm: false,
                    onConfirm: function (e) {
                        var uploadFile = $("#uploadFile").val();
                        if (!uploadFile) {
                            return alert("请选择需要上传的文件");
                        }
                        if (!/.[C|c][S|s][V|v]?$/i.test(uploadFile)) {
                            alert("请选择csv文件上传");
                            $("#uploadFile").val("");
                            return false;
                        }
                        submitFileForm();
                        $('#my-prompt').modal('close');
                    },
                    onCancel: function (e) {
                        $("#uploadFile").val("");
                    }
                });
            });
        });

        init();
    }]);

// 题库管理
app
    .controller(
        "admin-question",
        [
            "$scope",
            "$http",
            "$q",
            "basicinfo",
            "dialog",
            function ($scope, $http, $q, basicinfo, dialog) {
                $scope.currentItem = {};
                $scope.batchItem = {};
                $scope.reverscates = {};
                $scope.reversseqs = {};
                $scope.checkall = false;
                $scope.itemtypes = testitemtype;
                $scope.difficulties = difficulties;
                $scope.reversdifficulties = arrayToReverseMap(
                    difficulties, "value", "label");
                var getcates = function () {
                    var def = $q.defer();
                    basicinfo
                        .getcates()
                        .then(
                            function (data) {
                                $scope.cates = data;
                                $scope.reverscates = arrayToReverseMap(
                                    data, "catebh",
                                    "catename");
                                def.resolve();
                            }, function () {
                                def.reject("请分类列表数据错误");
                            });
                    return def.promise;
                };

                var getseqs = function () {
                    var def = $q.defer();
                    basicinfo
                        .getseqs()
                        .then(
                            function (data) {
                                $scope.seqs = data;
                                $scope.reversseqs = arrayToReverseMap(
                                    data, "seqbh",
                                    "seqname");
                                def.resolve();
                            }, function () {
                                def.reject("请序列列表数据错误");
                            });
                    return def.promise;
                };

                var init = function () {
                    getseqs().then(getcates);
                };

                var sampleOpt = [{
                    "optno": "A",
                    "optcontent": "",
                    "isanswer": false,
                    "truefalse": "√"
                }, {
                    "optno": "B",
                    "optcontent": "",
                    "isanswer": false,
                    "truefalse": "X"
                }, {
                    "optno": "C",
                    "optcontent": "",
                    "isanswer": false
                }, {
                    "optno": "D",
                    "optcontent": "",
                    "isanswer": false
                }];

                $scope.importQuestion = function () {
                    $scope.batchItem = {};
                    $("#doc-modal-2").modal('open');
                };

                $scope.batchImport = function () {
                    if (!$scope.batchItem.itemseq) {
                        return alert("请选择序列");
                    }
                    if (!$scope.batchItem.itemcate) {
                        return alert("请选择分类");
                    }
                    var batchFile = $("#batchFile").val();
                    if (!batchFile) {
                        return alert("请选择需要上传的文件");
                    }
                    if (!/.[X|x][L|L][S|s][X|x]?$/i.test(batchFile)) {
                        return alert("请选择Excel文件上传");
                    }
                    submitFileForm();
                };

                var submitFileForm = function (callback) {
                    var submitForm = document
                        .getElementById("submitFile");
                    var iframe = document.createElement("iframe");
                    iframe.width = 0;
                    iframe.height = 0;
                    iframe.border = 0;
                    iframe.name = "form-iframe";
                    iframe.id = "form-iframe";
                    iframe.setAttribute("style",
                        "width:0;height:0;border:none");
                    // 放到document
                    submitForm.appendChild(iframe);
                    submitForm.action = "./batchQuestion";
                    submitForm.target = "form-iframe";
                    iframe.onload = function () {
                        // 获取iframe的内容，即服务返回的数据
                        var responseData = this.contentDocument.body.textContent
                            || this.contentWindow.document.body.textContent;
                        try {
                            var resultJson = JSON
                                .parse(responseData);
                            if (resultJson.status == "ok") {
                                alert("导入成功");
                                $("#doc-modal-2").modal('close');
                                // $scope.search();
                            } else {
                                alert("导入失败");
                            }
                        } catch (e) {
                            alert("导入失败");
                        } finally {
                            // 删掉iframe
                            setTimeout(
                                function () {
                                    var _frame = document
                                        .getElementById("form-iframe");
                                    _frame.parentNode
                                        .removeChild(_frame);
                                }, 200);
                        }
                    }
                    submitForm.submit();
                };

                $scope.add = function () {
                    $scope.currentItem = {};
                    $scope.currentOptions = sampleOpt;
                    $("#doc-modal-1").modal('open');
                };

                $scope.edit = function (item) {
                    $scope.currentItem = item;
                    $http
                        .get(
                            "./getoptions?itembh="
                            + encodeURI(item.itembh))
                        .success(
                            function (data) {
                                if (data.length == 0)
                                    $scope.currentOptions = sampleOpt;
                                else
                                    $scope.currentOptions = data;
                                for (var i = 0, j = $scope.currentOptions.length; i < j; i++) {
                                    var opt = $scope.currentOptions[i];
                                    if (item.itemtype == "判断题") {
                                        opt.truefalse = opt.optcontent;
                                    }
                                    if (opt.isanswer == 1) {
                                        opt.isanswer = true;
                                    } else {
                                        opt.isanswer = false;
                                    }
                                }
                                $("#doc-modal-1").modal(
                                    'open');
                            }).error(function () {
                        alert("获取题目答案失败");
                    });
                };

                $scope.deleteItem = function (item) {
                    dialog.confirm("您真的要删除 " + item.itemcontent
                        + " 吗？", function () {
                        $http.get(
                            "./deletequestion?itembh="
                            + encodeURI(item.itembh))
                            .success(function (data) {
                                if (data.status == "ok")
                                    $scope.search();
                                else
                                    dialog.alert("题目删除失败");
                            }).error(function () {
                            alert("题目删除失败");
                        });
                    });
                };

                var postitemcontent = function () {
                    var def = $q.defer();
                    $http.post("./postquestiondata",
                        $scope.currentItem).success(
                        function (data) {
                            if (data.status == "ok") {
                                def.resolve(data.info);
                            }
                        }).error(function () {
                        def.reject("更新题库数据错误");
                    });
                    return def.promise;
                };

                var postitemoption = function (bh) {
                    var def = $q.defer();
                    var items = $scope.currentOptions;
                    var itemtype = $scope.currentItem.itemtype;
                    if (itemtype == "判断题") {
                        items = items.splice(0, 2);
                    }
                    for (var i = 0, j = items.length; i < j; i++) {
                        var item = items[i];
                        item.itembh = bh;
                        if (itemtype == "判断题") {
                            if (i == 0) {
                                item.optcontent = "√";
                            }
                            if (i == 1) {
                                item.optcontent = "X";
                            }
                        }
                        if (item.isanswer === false) {
                            item.isanswer = 0;
                        } else {
                            item.isanswer = 1;
                        }
                    }
                    $http.post("./postoptions", items).success(
                        function (data) {
                            if (data.status == "ok") {
                                def.resolve();
                            }
                        }).error(function () {
                        def.reject("更新题库数据错误");
                    });
                    return def.promise;
                }

                $scope.postData = function () {
                    postitemcontent().then(postitemoption).then(
                        function () {
                            $scope.search();
                            $("#doc-modal-1").modal('close');
                        });
                };

                $scope.search = function () {
                    var url = "./getquestions?t=fix";
                    if ($scope.qseq) {
                        url += "&seqbh=" + encodeURI($scope.qseq);
                    }
                    if ($scope.qcate) {
                        url += "&catebh=" + encodeURI($scope.qcate);
                    }
                    $http.get(url).success(function (data) {
                        $scope.items = data;
                    }).error(function () {
                        alert("查询题库数据错误");
                    });
                };

                $scope
                    .$watch(
                        "checkall",
                        function (v) {
                            for (var i = 0, j = $scope.items.length; i < j; i++) {
                                var item = $scope.items[i];
                                item.checked = v;
                            }
                        });

                $scope.deleteQuestion = function () {
                    var ids = [];
                    for (var i = 0, j = $scope.items.length; i < j; i++) {
                        var item = $scope.items[i];
                        if (item.checked) {
                            ids.push(item.itembh);
                        }
                    }
                    if (ids.length == 0) {
                        dialog.alert("没有选择需要删除的题目");
                        return;
                    }
                    dialog.confirm("您真的要删除选择的题目吗？", function () {
                        $http.post("./deleteQuestions",
                            encodeURI(ids.join(";"))).success(
                            function (data) {
                                if (data.status == "ok") {
                                    dialog.alert("题目删除成功");
                                } else {
                                    dialog.alert("题目删除失败");
                                }
                            }).error(function () {
                            dialog.alert("题目删除失败");
                        });
                    });
                };

                init();
            }]);

// 考试计划
app
    .controller(
        "admin-plan",
        [
            "$scope",
            "$http",
            "$q",
            "basicinfo",
            "dialog",
            function ($scope, $http, $q, basicinfo, dialog) {
                var d = new Date().getYear() + 1900;
                $scope.nds = [];
                $scope.currentDetails = [];
                $scope.difficulties = difficulties;
                $scope.types = testitemtype;
                for (var i = d; i > d - 10; i--) {
                    $scope.nds.push(i);
                }

                $scope.addoredit = false;

                var getcates = function () {
                    var def = $q.defer();
                    basicinfo.getcates().then(function (data) {
                        $scope.cates = data;
                        def.resolve();
                    }, function () {
                        def.reject("请分类列表数据错误");
                    });
                    return def.promise;
                };

                var getseqs = function () {
                    var def = $q.defer();
                    basicinfo.getseqs().then(function (data) {
                        $scope.seqs = data;
                        def.resolve();
                    }, function () {
                        def.reject("请序列列表数据错误");
                    });
                    return def.promise;
                };

                $scope.add = function () {
                    $scope.currentItem = {};
                    $scope.currentDetails = [];
                    $scope.addoredit = true;
                };

                var getmodeldetail = function () {
                    var bh = $scope.currentItem.modelbh;
                    if (bh == null)
                        return;
                    $http.get(
                        "./getmodeldetail?modelbh="
                        + encodeURI(bh)).success(
                        function (data) {
                            $scope.currentDetails = data;
                        }).error(function () {
                        alert("获取计划明细信息失败");
                    });
                };

                $scope.edit = function (item) {
                    $scope.currentItem = item;
                    getmodeldetail();
                    $scope.addoredit = true;
                };

                var postmodel = function () {
                    var def = $q.defer();
                    $http.post("./postplans", $scope.currentItem)
                        .success(function (data) {
                            if (data.status == "ok") {
                                var bh = data.info;
                                def.resolve(bh);
                            }
                        }).error(function () {
                        def.reject("保存主计划出错");
                    });
                    return def.promise;
                };

                var deletewithmodelbh = function (bh) {
                    var def = $q.defer();
                    $http.get(
                        "./deletewithmodelbh?modelbh="
                        + encodeURI(bh)).success(
                        function (data) {
                            if (data.status == "ok") {
                                def.resolve(bh);
                            }
                        }).error(function () {
                        def.reject("保存主计划出错");
                    });
                    return def.promise;
                };

                var prepostmodeldetail = function () {
                    var items = $scope.currentDetails;
                    if (items.length == 0)
                        return false;
                    for (var i = 0, j = items.length; i < j; i++) {
                        var item = items[i];
                        if (!item.itemtype) {
                            return false;
                        }
                    }
                    return true;
                };

                var postmodeldetail = function (bh) {
                    var def = $q.defer();
                    var items = $scope.currentDetails;
                    for (var i = 0, j = items.length; i < j; i++) {
                        var item = items[i];
                        delete item.detailbh;
                        item.modelbh = bh;
                    }
                    $http.post("./postplandetails", items).success(
                        function (data) {
                            if (data.status == "ok") {
                                def.resolve();
                            }
                        }).error(function () {
                        def.reject("保存主计划出错");
                    });
                    return def.promise;
                };

                $scope.postData = function () {
                    if (!prepostmodeldetail()) {
                        dialog.alert("题型必须选择，请选择后再提交");
                    } else {
                        postmodel().then(deletewithmodelbh).then(
                            postmodeldetail).then(function () {
                            $scope.addoredit = false;
                            $scope.search();
                        }, function () {
                            alert("计划保存失败");
                            $scope.addoredit = false;
                        });
                    }
                };

                $scope.cancel = function () {
                    $scope.addoredit = false;
                };

                var init = function () {
                    getseqs().then(getcates);
                };

                $scope.addDetail = function () {
                    $scope.currentDetails.push({});
                };

                $scope.deleteDetail = function (a) {
                    $scope.currentDetails.splice(a, 1);
                };

                $scope.calcScore = function () {
                    var items = $scope.currentDetails;
                    var total = 0;
                    for (var i = 0, j = items.length; i < j; i++) {
                        var item = items[i];
                        var c = item.itemcount || 0, av = item.score || 0;
                        total += c * av;
                    }
                    dialog.alert("总分数： " + total);
                };

                $scope.search = function () {
                    var url = "./getplans?t=t";
                    if ($scope.qnd) {
                        url += "&nd=" + $scope.qnd;
                    }
                    if ($scope.qseq) {
                        url += "&seqbh=" + $scope.qseq;
                    }
                    if ($scope.qcate) {
                        url += "&catebh=" + $scope.qcate;
                    }
                    $http.get(url).success(function (data) {
                        $scope.items = data;
                    }).error(function () {
                        alert("获取计划失败");
                    });
                };

                $scope.build = function (item) {
                    dialog
                        .confirm(
                            "您真的要生成试卷模板吗？此操作将耗费一定时间，请耐心等待。",
                            function () {
                                $http
                                    .get(
                                        "./buildtest?modelbh="
                                        + encodeURI(item.modelbh))
                                    .success(
                                        function (
                                            data) {
                                            if (data.status == "ok") {
                                                dialog
                                                    .alert("试卷生成操作成功");
                                                $scope
                                                    .search();
                                            } else
                                                dialog
                                                    .alert("试卷生成操作失败\n"
                                                        + data.msg);
                                        })
                                    .error(
                                        function () {
                                            alert("试卷生成操作失败\n网络原因");
                                        });
                            });
                };

                $scope.rebuild = function (item) {
                    dialog
                        .confirm(
                            "您真的要重新生成试卷模板吗？原有的试卷模板将被清除。",
                            function () {
                                $http
                                    .get(
                                        "./rebuildtest?modelbh="
                                        + encodeURI(item.modelbh))
                                    .success(
                                        function (
                                            data) {
                                            if (data.status == "ok") {
                                                dialog
                                                    .alert("试卷生成操作成功");
                                                $scope
                                                    .search();
                                            } else
                                                dialog
                                                    .alert("试卷生成操作失败 ["
                                                        + data.msg
                                                        + "]");
                                        })
                                    .error(
                                        function () {
                                            alert("试卷生成操作失败");
                                        });
                            });

                };

                $scope.deleteItem = function (item) {
                    dialog
                        .confirm(
                            "作废的试卷模板将不能编辑，不能使用，您真得要作废吗？",
                            function () {
                                $http
                                    .get(
                                        "./disabletest?modelbh="
                                        + encodeURI(item.modelbh))
                                    .success(
                                        function (
                                            data) {
                                            if (data.status == "ok") {
                                                dialog
                                                    .alert("试卷作废操作成功");
                                                $scope
                                                    .search();
                                            } else
                                                dialog
                                                    .alert("试卷作废操作失败 ["
                                                        + data.msg
                                                        + "]");
                                        })
                                    .error(
                                        function () {
                                            alert("试卷作废操作失败");
                                        });
                            });
                }

                $scope.deleteModel = function (item) {
                    dialog
                        .confirm(
                            "删除作废试卷，将同时删除其所有关联的考试试卷，您真得要删除吗？",
                            function () {
                                $http
                                    .get(
                                        "./deletemodel?modelbh="
                                        + encodeURI(item.modelbh))
                                    .success(
                                        function (
                                            data) {
                                            if (data.status == "ok") {
                                                dialog
                                                    .alert("试卷删除操作成功");
                                                $scope
                                                    .search();
                                            } else
                                                dialog
                                                    .alert("试卷删除操作失败 ["
                                                        + data.msg
                                                        + "]");
                                        })
                                    .error(
                                        function () {
                                            alert("试卷删除操作失败");
                                        });
                            });
                };

                $scope.view = function (item) {
                    window.open("../mytest?modelbh="
                        + encodeURI(item.modelbh)
                        + "&full=full");
                };

                $scope.cloneItem = function (item) {
                    dialog
                        .confirm(
                            "你要以本计划为模板，再生成一个计划吗？",
                            function () {
                                $http
                                    .get(
                                        "./cloneitem?modelbh="
                                        + encodeURI(item.modelbh))
                                    .success(
                                        function (
                                            data) {
                                            if (data.status == "ok") {
                                                dialog
                                                    .alert("试卷克隆操作成功");
                                                $scope
                                                    .search();
                                            } else
                                                dialog
                                                    .alert("试卷克隆操作失败 ["
                                                        + data.msg
                                                        + "]");
                                        })
                                    .error(
                                        function () {
                                            alert("试卷删除操作失败");
                                        });
                            });
                };

                $scope.getItemCount = function (item) {
                    /*
								 * "itemlevel":1,"seqbh":"cca98cc0-8b53-4e7d-bd31-8b241ddd0a83","score":4,"detailbh":"d041d6d5-d8a7-45f5-92e1-fae61b6eebb5","itemtype":"单选题","catebh":"c230ad74-cf68-4639-bf06-ea4ee111f202","itemcount":3,"modelbh":"ba1fbd75-f0e1-4147-932d-a23ec626dabb","$hashKey":"008"
								 */
                    $http
                        .get(
                            "./gettestitemcount?itemlevel="
                            + (item.itemlevel ? item.itemlevel
                            : "")
                            + "&seqbh="
                            + (item.seqbh ? item.seqbh
                            : "")
                            + "&itemtype="
                            + (item.itemtype ? item.itemtype
                            : "")
                            + "&catebh="
                            + (item.catebh ? item.catebh
                            : ""))
                        .success(
                            function (data) {
                                dialog
                                    .alert("当前题型在题库中的数量： "
                                        + data);
                            }).error(function () {
                        dialog.alert("请求数据失败");
                    });
                };

                init();
            }]);

// 考试人员授权管理
app
    .controller(
        "admin-testauth",
        [
            "$scope",
            "$http",
            "$q",
            "basicinfo",
            "dialog",
            function ($scope, $http, $q, basicinfo, dialog) {
                var url = location.href;
                var typeint = 3;
                if (url.indexOf("yjauth") >= 0) {
                    typeint = 2;
                }
                $scope.currentItem = {};
                $scope.authopt = false;
                $scope.data = toporganize;

                $scope.sexs = personsexs;

                $scope.checkall = false;
                $scope.orgs = [];
                $scope.orgPathMaps = [];

                var d = new Date().getYear() + 1900;
                $scope.nds = [];
                $scope.currentDetails = [];
                $scope.types = testitemtype;
                for (var i = d; i > d - 10; i--) {
                    $scope.nds.push(i);
                }

                var snapshot = {};
                var buildTreeData = function (data, currentNode,
                                              orgtitle) {
                    var attr = currentNode.ext;
                    if (!orgtitle) {
                        currentNode.path = currentNode.title;
                    } else {
                        currentNode.path = orgtitle + "/"
                            + currentNode.title;
                    }
                    $scope.orgs.push(currentNode);
                    $scope.orgPathMaps[attr] = currentNode.path;
                    snapshot[attr || "--"] = currentNode;
                    if (attr == "") { // root
                        for (var i = 0, j = data.length; i < j; i++) {
                            var item = data[i];
                            var a = item.parentbh;
                            if (!a) {
                                var arr = currentNode.subs;
                                if (!arr) {
                                    arr = [];
                                    currentNode.subs = arr;
                                }
                                var a = {};
                                a.title = item.orgname;
                                a.ext = item.orgbh;
                                a.type = "item";
                                arr.push(a);
                                buildTreeData(data, a,
                                    currentNode.path);
                            }
                        }
                    } else {
                        for (var i = 0, j = data.length; i < j; i++) {
                            var item = data[i];
                            var a = item.parentbh;
                            if (a == currentNode.ext) {
                                var arr = currentNode.subs;
                                if (!arr) {
                                    arr = [];
                                    currentNode.subs = arr;
                                }
                                var a = {};
                                a.title = item.orgname;
                                a.ext = item.orgbh;
                                a.type = "item";
                                arr.push(a);
                                buildTreeData(data, a,
                                    currentNode.path);
                            }
                        }
                    }
                    if (currentNode.subs
                        && currentNode.subs.length > 0) {
                        currentNode.type = "folder";
                    } else {
                        currentNode.type = "item";
                    }
                };

                var buildTree = function () {
                    $('#firstTree').tree(
                        {
                            dataSource: function (options,
                                                  callback) {
                                try {
                                    callback({
                                        data: options.subs
                                        || $scope.data
                                    });
                                } catch (e) {

                                }
                            },
                            multiSelect: false,
                            cacheItems: false,
                            folderSelect: true
                        }).tree('discloseAll');
                };

                var getorganizes = function () {
                    var def = $q.defer();
                    basicinfo.getorgs().then(function (data) {
                        buildTreeData(data, $scope.data[0]);
                        buildTree();
                        def.resolve();
                    }, function () {
                        def.reject("请求机构列表数据错误");
                    });
                    return def.promise;
                };

                var getlevels = function () {
                    var def = $q.defer();
                    basicinfo.getlevels().then(function (data) {
                        $scope.levels = data;
                        def.resolve();
                    }, function () {
                        def.reject("请求职级列表数据错误");
                    });
                    return def.promise;
                };

                var getcates = function () {
                    var def = $q.defer();
                    basicinfo.getcates().then(function (data) {
                        $scope.cates = data;
                        def.resolve();
                    }, function () {
                        def.reject("请分类列表数据错误");
                    });
                    return def.promise;
                };

                var getseqs = function () {
                    var def = $q.defer();
                    basicinfo.getseqs().then(function (data) {
                        $scope.seqs = data;
                        def.resolve();
                    }, function () {
                        def.reject("请序列列表数据错误");
                    });
                    return def.promise;
                };

                var init = function () {
                    getseqs().then(getcates).then(getlevels).then(
                        getorganizes);
                };

                $scope.checkAll = function () {
                    var items = $scope.persons;
                    $scope.checkall = !$scope.checkall;
                    for (var i = 0, j = items.length; i < j; i++) {
                        var item = items[i];
                        item.checked = $scope.checkall;
                    }
                };

                $scope.search = function () {
                    var url = "./getplans?t=t";
                    if ($scope.qnd) {
                        url += "&nd=" + $scope.qnd;
                    }
                    if ($scope.qseq) {
                        url += "&seqbh=" + $scope.qseq;
                    }
                    if ($scope.qcate) {
                        url += "&catebh=" + $scope.qcate;
                    }
                    $http.get(url).success(function (data) {
                        $scope.items = data;
                    }).error(function () {
                        alert("获取计划失败");
                    });
                };

                $scope.edit = function (item) {
                    $scope.currentItem = item;
                    $http.get(
                        "./getauthusers?type=" + typeint
                        + "&bh="
                        + encodeURI(item.modelbh))
                        .success(function (data) {
                            $scope.currentAuths = data;
                            $scope.authopt = true;
                        }).error(function () {
                        alert("获取授权资源信息失败");
                    });
                };

                $scope.cancel = function () {
                    $scope.currentAuths = [];
                    $scope.authopt = false;
                };

                var personInAuth = function (person) {
                    var bh = person.userbh;
                    for (var i = 0, j = $scope.currentAuths.length; i < j; i++) {
                        var p = $scope.currentAuths[i];
                        if (p.userbh == bh) {
                            return true;
                        }
                    }
                    return false;
                };

                $scope.addperson = function () {
                    for (var i = 0, j = $scope.persons.length; i < j; i++) {
                        var p = $scope.persons[i];
                        if (p.checked && !personInAuth(p)) {
                            var item = {};
                            item.userbh = p.userbh;
                            item.username = p.username;
                            item.realname = p.realname;
                            $scope.currentAuths.push(item);
                        }
                    }
                };
                $scope.deleteperson = function () {
                    for (var i = $scope.currentAuths.length - 1, j = 0; i >= j; i--) {
                        var p = $scope.currentAuths[i];
                        if (p.checked) {
                            $scope.currentAuths.splice(i, 1);
                        }
                    }
                };

                var deleteauthwithres = function () {
                    var def = $q.defer();
                    $http
                        .get(
                            "./deleteauthwithres?type="
                            + typeint
                            + "&bh="
                            + encodeURI($scope.currentItem.modelbh))
                        .success(function (data) {
                            def.resolve();
                        }).error(function () {
                        def.reject("请序列列表数据错误");
                    });
                    return def.promise;
                };

                var postauthentic = function () {
                    var def = $q.defer();
                    var items = [];
                    for (var i = 0, j = $scope.currentAuths.length; i < j; i++) {
                        var item = $scope.currentAuths[i];
                        var postItem = {};
                        postItem.authvalue = typeint;
                        postItem.resourcebh = $scope.currentItem.modelbh;
                        postItem.userbh = item.userbh;
                        items.push(postItem);
                    }
                    $http.post("./postauthentics", items).success(
                        function (data) {
                            def.resolve();
                        }).error(function () {
                        def.reject("请序列列表数据错误");
                    });
                    return def.promise;
                };

                $scope.postData = function () {
                    deleteauthwithres().then(postauthentic).then(
                        function () {
                            $scope.currentAuths = [];
                            $scope.authopt = false;
                        });
                };

                treeSelectedEvent("firstTree",
                    function (event, data) {
                        if (data.target) {
                            var attr = data.target.ext || "--";
                            $scope.currentOrg = snapshot[attr];
                            var url = "./getpersonlist";
                            if (attr != "--") {
                                url += "?orgbh="
                                    + encodeURI(attr);
                            }
                            $http.get(url).success(
                                function (data) {
                                    $scope.persons = data;
                                }).error(function () {
                                alert("获取用户数据失败");
                            });
                        }
                    });

                init();
            }]);

// 超级管理员授权管理
app
    .controller(
        "admin-adminauth",
        [
            "$scope",
            "$http",
            "$q",
            "basicinfo",
            "dialog",
            function ($scope, $http, $q, basicinfo, dialog) {
                var typeint = 1;
                $scope.currentItem = {};
                $scope.authopt = false;
                $scope.data = toporganize;

                $scope.sexs = personsexs;

                $scope.checkall = false;
                $scope.orgs = [];
                $scope.orgPathMaps = [];

                var d = new Date().getYear() + 1900;
                $scope.nds = [];
                $scope.currentDetails = [];
                $scope.types = testitemtype;
                for (var i = d; i > d - 10; i--) {
                    $scope.nds.push(i);
                }

                var snapshot = {};
                var buildTreeData = function (data, currentNode,
                                              orgtitle) {
                    var attr = currentNode.ext;
                    if (!orgtitle) {
                        currentNode.path = currentNode.title;
                    } else {
                        currentNode.path = orgtitle + "/"
                            + currentNode.title;
                    }
                    $scope.orgs.push(currentNode);
                    $scope.orgPathMaps[attr] = currentNode.path;
                    snapshot[attr || "--"] = currentNode;
                    if (attr == "") { // root
                        for (var i = 0, j = data.length; i < j; i++) {
                            var item = data[i];
                            var a = item.parentbh;
                            if (!a) {
                                var arr = currentNode.subs;
                                if (!arr) {
                                    arr = [];
                                    currentNode.subs = arr;
                                }
                                var a = {};
                                a.title = item.orgname;
                                a.ext = item.orgbh;
                                a.type = "item";
                                arr.push(a);
                                buildTreeData(data, a,
                                    currentNode.path);
                            }
                        }
                    } else {
                        for (var i = 0, j = data.length; i < j; i++) {
                            var item = data[i];
                            var a = item.parentbh;
                            if (a == currentNode.ext) {
                                var arr = currentNode.subs;
                                if (!arr) {
                                    arr = [];
                                    currentNode.subs = arr;
                                }
                                var a = {};
                                a.title = item.orgname;
                                a.ext = item.orgbh;
                                a.type = "item";
                                arr.push(a);
                                buildTreeData(data, a,
                                    currentNode.path);
                            }
                        }
                    }
                    if (currentNode.subs
                        && currentNode.subs.length > 0) {
                        currentNode.type = "folder";
                    } else {
                        currentNode.type = "item";
                    }
                };

                var buildTree = function () {
                    $('#firstTree').tree(
                        {
                            dataSource: function (options,
                                                  callback) {
                                try {
                                    callback({
                                        data: options.subs
                                        || $scope.data
                                    });
                                } catch (e) {

                                }
                            },
                            multiSelect: false,
                            cacheItems: false,
                            folderSelect: true
                        }).tree('discloseAll');
                };

                var getorganizes = function () {
                    var def = $q.defer();
                    basicinfo.getorgs().then(function (data) {
                        buildTreeData(data, $scope.data[0]);
                        buildTree();
                        def.resolve();
                    }, function () {
                        def.reject("请求机构列表数据错误");
                    });
                    return def.promise;
                };

                var getlevels = function () {
                    var def = $q.defer();
                    basicinfo.getlevels().then(function (data) {
                        $scope.levels = data;
                        def.resolve();
                    }, function () {
                        def.reject("请求职级列表数据错误");
                    });
                    return def.promise;
                };

                var getcates = function () {
                    var def = $q.defer();
                    basicinfo.getcates().then(function (data) {
                        $scope.cates = data;
                        def.resolve();
                    }, function () {
                        def.reject("请分类列表数据错误");
                    });
                    return def.promise;
                };

                var getseqs = function () {
                    var def = $q.defer();
                    basicinfo.getseqs().then(function (data) {
                        $scope.seqs = data;
                        def.resolve();
                    }, function () {
                        def.reject("请序列列表数据错误");
                    });
                    return def.promise;
                };

                var init = function () {
                    getseqs().then(getcates).then(getlevels).then(
                        getorganizes);
                };

                $scope.checkAll = function () {
                    var items = $scope.persons;
                    $scope.checkall = !$scope.checkall;
                    for (var i = 0, j = items.length; i < j; i++) {
                        var item = items[i];
                        item.checked = $scope.checkall;
                    }
                };

                $http.get("./getauthusers?type=" + typeint)
                    .success(function (data) {
                        $scope.currentAuths = data;
                    }).error(function () {
                    alert("获取授权资源信息失败");
                });

                var personInAuth = function (person) {
                    var bh = person.userbh;
                    for (var i = 0, j = $scope.currentAuths.length; i < j; i++) {
                        var p = $scope.currentAuths[i];
                        if (p.userbh == bh) {
                            return true;
                        }
                    }
                    return false;
                };

                $scope.addperson = function () {
                    for (var i = 0, j = $scope.persons.length; i < j; i++) {
                        var p = $scope.persons[i];
                        if (p.checked && !personInAuth(p)) {
                            var item = {};
                            item.userbh = p.userbh;
                            item.username = p.username;
                            item.realname = p.realname;
                            $scope.currentAuths.push(item);
                        }
                    }
                };

                $scope.deleteperson = function () {
                    for (var i = $scope.currentAuths.length - 1, j = 0; i >= j; i--) {
                        var p = $scope.currentAuths[i];
                        if (p.checked) {
                            $scope.currentAuths.splice(i, 1);
                        }
                    }
                };

                var deleteauthwithres = function () {
                    var def = $q.defer();
                    $http
                        .get(
                            "./deleteauthwithres?type="
                            + typeint).success(
                        function (data) {
                            def.resolve();
                        }).error(function () {
                        def.reject("请序列列表数据错误");
                    });
                    return def.promise;
                };

                var postauthentic = function () {
                    var def = $q.defer();
                    var items = [];
                    for (var i = 0, j = $scope.currentAuths.length; i < j; i++) {
                        var item = $scope.currentAuths[i];
                        var postItem = {};
                        postItem.authvalue = typeint;
                        postItem.userbh = item.userbh;
                        items.push(postItem);
                    }
                    $http.post("./postauthentics", items).success(
                        function (data) {
                            def.resolve();
                        }).error(function () {
                        def.reject("请序列列表数据错误");
                    });
                    return def.promise;
                };

                $scope.postData = function () {
                    deleteauthwithres().then(postauthentic).then(
                        function () {
                            dialog.alert("设置成功");
                        });
                };

                treeSelectedEvent("firstTree",
                    function (event, data) {
                        if (data.target) {
                            var attr = data.target.ext || "--";
                            $scope.currentOrg = snapshot[attr];
                            var url = "./getpersonlist";
                            if (attr != "--") {
                                url += "?orgbh="
                                    + encodeURI(attr);
                            }
                            $http.get(url).success(
                                function (data) {
                                    $scope.persons = data;
                                }).error(function () {
                                alert("获取用户数据失败");
                            });
                        }
                    });

                init();
            }]);

// 导航页面
app.controller("index-nav", ["$scope", "$http", "$q", "basicinfo", "dialog",
    function ($scope, $http, $q, basicinfo, dialog) {
        $scope.showadmin = false;
        $scope.showyj = false;
        $scope.showtest = false;
        $scope.systemtitle = g_systemtitle;

        var init = function () {
            basicinfo.getmyinfo().then(function (data) {
                $scope.realname = data.realname;
                $scope.userbh = data.userbh;
                var auths = data.auths;
                for (var i = 0, j = auths.length; i < j; i++) {
                    var v = auths[i];
                    if (v == 1) {
                        $scope.showadmin = true;
                    }
                    if (v == 2) {
                        $scope.showyj = true;
                    }
                    if (v == 3) {
                        $scope.showtest = true;
                    }
                }
            });
        };

        $scope.go2admin = function () {
            location.href = "./mgr/admin";
        };

        $scope.go2yj = function () {
            location.href = "./yj/index";
        };

        setTimeout(function () {
            if (location.href.indexOf("myinfo") != -1) {
                return;
            }
            if ($scope.realname == '未命名') {
                alert("您的个人信息尚未完善，请先完善个人信息！")
                location.href = "./myinfo";
            }
            if ($scope.realname == 'audittest') {
                return;
            }
        }, 1000);

        $scope.go2test = function () {
            if ($scope.realname == '未命名') {
                alert("您的个人信息尚未完善，请先完善个人信息！")
                location.href = "./myinfo";
            } else if ($scope.realname == 'audittest') {
                location.href = "./testnav";
            } else {
                location.href = "./testnav";
            }
        };

        $scope.go2score = function () {
            location.href = "./testscore";
        };
        init();
    }]);

// 个人信息
app.controller("myinfo", [
    "$scope",
    "$http",
    "$q",
    "basicinfo",
    "dialog",
    function ($scope, $http, $q, basicinfo, dialog) {

        $scope.data = toporganize;

        $scope.sexs = personsexs;
        $scope.newpasswd = "";
        $scope.newpasswd2 = "";
        $scope.orgs = [];
        $scope.orgPathMaps = [];
        $scope.edu = ["专科", "三本", "二本", "一本", "研究生", "其他"];

        var snapshot = {};
        var buildTreeData = function (data, currentNode, orgtitle) {
            var attr = currentNode.ext;
            if (!orgtitle) {
                currentNode.path = currentNode.title;
            } else {
                currentNode.path = orgtitle + "/" + currentNode.title;
            }
            $scope.orgs.push(currentNode);
            $scope.orgPathMaps[attr] = currentNode.path;
            snapshot[attr || "--"] = currentNode;
            if (attr == "") { // root
                for (var i = 0, j = data.length; i < j; i++) {
                    var item = data[i];
                    var a = item.parentbh;
                    if (!a) {
                        var arr = currentNode.subs;
                        if (!arr) {
                            arr = [];
                            currentNode.subs = arr;
                        }
                        var a = {};
                        a.title = item.orgname;
                        a.ext = item.orgbh;
                        a.type = "item";
                        arr.push(a);
                        buildTreeData(data, a, currentNode.path);
                    }
                }
            } else {
                for (var i = 0, j = data.length; i < j; i++) {
                    var item = data[i];
                    var a = item.parentbh;
                    if (a == currentNode.ext) {
                        var arr = currentNode.subs;
                        if (!arr) {
                            arr = [];
                            currentNode.subs = arr;
                        }
                        var a = {};
                        a.title = item.orgname;
                        a.ext = item.orgbh;
                        a.type = "item";
                        arr.push(a);
                        buildTreeData(data, a, currentNode.path);
                    }
                }
            }
            if (currentNode.subs && currentNode.subs.length > 0) {
                currentNode.type = "folder";
            } else {
                currentNode.type = "item";
            }
        };

        var getmyself = function () {
            var def = $q.defer();
            $http.get("./getmyself").success(function (data) {
                $scope.currentItem = data;
                def.resolve();
            }).error(function () {
                def.reject("请求机构列表数据错误");
            });
            return def.promise;
        };

        var getorganizes = function () {
            var def = $q.defer();
            basicinfo.getorgs().then(function (data) {
                buildTreeData(data, $scope.data[0]);
                def.resolve();
            }, function () {
                def.reject("请求机构列表数据错误");
            });
            return def.promise;
        };

        var getlevels = function () {
            var def = $q.defer();
            basicinfo.getlevels().then(function (data) {
                $scope.levels = data;
                def.resolve();
            }, function () {
                def.reject("请求职级列表数据错误");
            });
            return def.promise;
        };

        var getcates = function () {
            var def = $q.defer();
            basicinfo.getcates().then(function (data) {
                $scope.cates = data;
                def.resolve();
            }, function () {
                def.reject("请分类列表数据错误");
            });
            return def.promise;
        };

        var getseqs = function () {
            var def = $q.defer();
            basicinfo.getseqs().then(function (data) {
                $scope.seqs = data;
                def.resolve();
            }, function () {
                def.reject("请序列列表数据错误");
            });
            return def.promise;
        };

        var init = function () {
            getmyself().then(getseqs).then(getcates).then(getlevels).then(
                getorganizes);
        };

        $scope.add = function () {
            $scope.currentItem = {};
            if ($scope.currentOrg != null) {
                $scope.currentItem.userdep = $scope.currentOrg.ext;
            }
            $("#doc-modal-1").modal('open');
        };

        $scope.edit = function (item) {
            $scope.currentItem = item;
            $("#doc-modal-1").modal('open');
        };

        $scope.deleteItem = function (item) {
            dialog.confirm("您真的要删除 " + item.username + " 吗？", function () {
                $http
                    .get(
                        "./deleteperson?userbh="
                        + encodeURI(item.userbh)).success(
                    function (data) {
                        if (data.status == "ok")
                            location.reload();
                        else
                            dialog.alert("人员删除失败");
                    }).error(function () {
                    alert("人员删除失败");
                });
            });
        };

        $scope.postData = function () {
            if ($scope.currentItem.realname == "" || $scope.currentItem.realname == null ||
                $scope.currentItem.education == "" || $scope.currentItem.education == null ||
                $scope.currentItem.schoolname == "" || $scope.currentItem.schoolname == null) {
                return alert("请将姓名，学历和学校填写完毕，进行考试");
            }
            $http.post("./postpersondata", $scope.currentItem).success(
                function (data) {
                    if (data.status == "ok")
                        location.reload();
                }).error(function () {
                alert("更新人员数据错误");
            });
        };

        $scope.resetPass = function () {
            dialog.confirm("您真的要重置密码吗？", function () {
                if ($scope.newpasswd != $scope.newpasswd2
                    && $scope.newpasswd != "") {
                    return dialog.alert("您两次输入的密码不正确，请重新设置");
                }
                var newpassobj = {};
                newpassobj.userbh = $scope.currentItem.userbh;
                newpassobj.passwd = $scope.newpasswd;
                $http.post("./setpass", newpassobj).success(function (data) {
                    if (data.status == "ok") {
                        dialog.alert("用户重置密码操作成功");
                    } else {
                        dialog.alert("用户重置密码操作失败");
                    }
                }).error(function () {
                    alert("用户重置密码操作失败");
                });
            });
        };

        init();
    }]);

// 考试入口导航
app.controller("test-nav", [
    "$scope",
    "$http",
    "basicinfo",
    function ($scope, $http, basicinfo) {
        $scope.items = [];
        $scope.showtest = true;
        var init = function () {
            basicinfo.getmyinfo().then(function (data) {
                $scope.realname = data.realname;
                $scope.userbh = data.userbh;
            });
            $http.get("./getmytests").success(function (data) {
                var items = [];
                for (var i = 0, j = data.length; i < j; i++) {
                    var d = data[i];
                    if (!d.enabled) {
                        items.push(d);
                    }
                }
                $scope.items = items;
            }).error(function () {
                alert("获取考试模板失败");
            });
        };
        init();

        $scope.go2test = function (item) {
            $('#my-confirm').modal(
                {
                    width: 640,
                    relatedTarget: this,
                    onConfirm: function (options) {
                        location.href = "./mytest?modelbh="
                            + encodeURI(item.modelbh);
                    },
                    // closeOnConfirm: false,
                    onCancel: function () {
                        alert('如果不同意，不能进行任职资格考试');
                    }
                });
        };
    }]);

// 考试
app.controller("test-main", [
    "$scope",
    "$http",
    "basicinfo",
    "$q",
    "dialog",
    function ($scope, $http, basicinfo, $q, dialog) {
        $scope.items = [];
        $scope.timeinvalid = "";
        $scope.finished = false;
        $scope.jumpPage = 1;
        $scope.questionList = [];//题目的数量
        $scope.singleWidth = 0;//单个题目的宽度

        var showModal = false;

        function showWarning() {
            if ($scope.finished) return;
            if (!showModal) {
                $("#my-modal-loading").modal("open");
                showModal = true;
                setTimeout(function () {
                    $("#my-modal-loading").modal("close");
                    showModal = false;
                }, 10000);
            }
        }

        document.addEventListener("visibilitychange", function () {
            showWarning();
        });

        $(window).resize(function () {
            showWarning();
        });

        var getmytestinfo = function () {
            var def = $q.defer();
            $http.get("./getmytestinfo").success(function (data) {
                $scope.cnt = data.cnt;
                $scope.singleWidth = 1000 / data.cnt;
                for (var i = 0; i < data.cnt; i++) {
                    $scope.questionList[i] = (i + 1);
                }
                $scope.modelname = data.modelname;
                $scope.starttime = data.starttime;
                $scope.minutes = data.minutes;
                $scope.finished = data.finished;
                def.resolve();
            }).error(function () {
                def.reject("获取考试信息失败");
            });
            return def.promise;
        };

        var inner_handler = function (step) {
            var def = $q.defer();
            $http.get("./getmytest?step=" + step).success(function (data) {
                if (data.length == 0) {
                    dialog.alert("您的题目有错误，可能没有选项，请确认题目没有问题再继续!");
                    return;
                }
                var item = data[0];
                $scope.itemcontent = item.itemcontent;
                $scope.itemtype = item.itemtype;
                $scope.score = item.score;
                $scope.sortno = item.sortno;
                for (var i = 0, j = data.length; i < j; i++) {
                    var d = data[i];
                    if (i == 0) {
                        d.truefalse = "√";
                    }
                    if (i == 1) {
                        d.truefalse = "X";
                    }
                    if (d.answer == "1") {
                        data[i].checked = true;
                    } else {
                        data[i].checked = false;
                    }
                }
                $scope.items = data;
                def.resolve();
            }).error(function () {
                def.reject("获取考试模板失败");
            });
            return def.promise;
        };

        var getmytest = function (step) {
            if (!step)
                step = 0;
            if (step == $scope.cnt && !$scope.finished) {
                dialog.confirm("您已经完成答卷！是否要交卷，交卷后不能再答卷了！", function () {
                    $http.get("./setmytestfinished").success(function () {
                        location.href = "."; // refresh
                    }).error(function () {
                        dialog.alert("交卷失败！");
                    });
                    dialog.alert("交卷成功！");
                }, function () {
                    step = 0;
                    return inner_handler(step);
                });
            } else if (step == $scope.cnt && $scope.finished) {
                step = 0;
                return inner_handler(step);
            } else {
                return inner_handler(step);
            }
        };

        // 交卷
        var postTest = function (step) {
            if (!step)
                step = 0;
            if (step == $scope.cnt && !$scope.finished) {
                dialog.confirm("您已经完成答卷！是否要交卷，交卷后不能再答卷了！", function () {
                    $http.get("./setmytestfinished1").success(function (data) {
                        location.href = "./fenshu"; // refresh
                    }).error(function () {
                        dialog.alert("交卷失败！");
                    });
                    dialog.alert("交卷成功！");
                });
            }
        };

        var saveitem = function (step) {
            var def = $q.defer();
            /*
				 * if ($scope.finished) { dialog.alert("当前考试已经结束！");
				 * def.resolve(step); return; }
				 */
            var opts = [];
            if ($scope.items[0].itemtype == "判断题") {
                if ($scope.items[0].checked && $scope.items[1].checked) {
                    def.reject("判断题不能都选中哦！");
                }
                if (!($scope.items[0].checked)
                    && !($scope.items[1].checked)) {
                    def.reject("判断题不能都不选哦！");
                }
            }
            for (var i = 0, j = $scope.items.length; i < j; i++) {
                var opt = {};
                var item = $scope.items[i];
                opt.testbh = item.testbh;
                opt.itembh = item.itembh;
                opt.optbh = item.optbh;
                opt.testoptbh = item.testoptbh;
                if (item.itemtype != "问答题" && item.itemtype != "名词解释"
                    && item.itemtype != "编程题" && item.itemtype != "主观题"
                    && item.itemtype != "填空题")
                    opt.answer = item.checked ? "1" : "0";
                else
                    opt.answer = item.answer;
                opts.push(opt);
            }

            $http.post("./postmytestitem", opts).success(function (data) {
                if (data.status == "ok") {
                    def.resolve(step);
                } else if (data.status == "outoftime") {
                    def.resolve(step);
                } else {
                    def.reject(data.msg);
                }
            }).error(function () {
                def.reject("保存当前答题信息失败");
            });
            return def.promise;
        };

        $scope.go2next = function () {
            if ($scope.finished) {
                return;
            }
            saveitem($scope.sortno + 1).then(getmytest, function (msg) {
                dialog.alert(msg);
            });
        };

        $scope.go2 = function (jumpPage) {
            if ($scope.finished) {
                return;
            }
            $scope.jumpPage = jumpPage;
            saveitem($scope.jumpPage - 1).then(getmytest, function (msg) {
                dialog.alert(msg);
            });
        };

        $scope.go2pre = function () {
            if ($scope.finished) {
                return;
            }
            saveitem($scope.sortno - 1).then(getmytest, function (msg) {
                dialog.alert(msg);
            });
        };

        $scope.changeColor = function (sortno) {//当选择答案时，变化当前题标的颜色
            $http.post("./saveColors?no=" + sortno).success(function (data) {
                $("#box" + sortno).css({"background": "#5eb95e"});
            })
        };
        var convertTime = function (t) {
            var p = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
                .exec(t);
            if (p) {
                return new Date(parseInt(p[1]), parseInt(p[2]),
                    parseInt(p[3]), parseInt(p[4]), parseInt(p[5]),
                    parseInt(p[6]));
            }
            return null;
        }

        $scope.jiaojuan = function () {
            saveitem($scope.cnt).then(postTest, function (msg) {
                dialog.alert(msg);
            });
        };

        $scope.quitTest = function () {
            if ($scope.finished) {
                return;
            }
            dialog.confirm("您确定要放弃考试吗？如放弃,成绩零分！", function () {
                $http.get("./setmytestfinished1?status=" + 0).success(function (data) {
                    location.href = "./fenshu"; // refresh
                }).error(function () {
                    dialog.alert("放弃考试失败！");
                });
                dialog.alert("放弃考试成功！");
            })
        };

        var printTimeInfo = function () {
            $http.get("./getnowtime").success(
                function (data) {
                    if (!$scope.minutes) {
                        return;
                    }
                    var sd = convertTime($scope.starttime).getTime()
                        + (parseInt($scope.minutes) * 1000 * 60);
                    var dd = convertTime(data).getTime();
                    if ($scope.finished || (dd > sd)) {
                        $scope.timeinfo = "";
                        $scope.timeinvalid = "考试时间已过/已经交卷";
                        $scope.finished = true;
                    } else {
                        var m = (parseInt(sd - dd) / (1000 * 60))
                            .toFixed(1);

                        var mm = zhuanhuan(60 * m);
                        //$scope.timeinfo = "考试还剩 " + mm + " 分钟";
                        var time = mm + "";
                        if (time.indexOf(".") != -1) {//找到字符串中有“.”，截取“.”之前的字符串
                            mm = time.substring(0, time.indexOf("."));
                        }
                        $scope.timeinfo = "倒计时:" + " " + mm;
                    }
                }).error(function () {
                alert("同步时间出错");
            });
        };

        var zhuanhuan = function (s) {
            var t;
            if (s > -1) {
                var hour = Math.floor(s / 3600);
                var min = Math.floor((s / 60) % 60);
                var sec = s % 60;
                if (hour < 10) {
                    t = '0' + hour + ":";
                }
                if (min < 10) {
                    t += "0";
                }
                t += min + ":";
                if (sec < 10) {
                    t += "0";
                }
                t += sec;
            }
            return t;
        };

        $scope.chakan = function () {
            if (/modelbh=(.*)$/.test(location.href)) {
                location.href = "./fenshu?modelbh=" + RegExp.$1;
            } else {
                alert("参数错误");
            }
        };

        var calcTime = function () {
            printTimeInfo();
            setInterval(printTimeInfo, 6000);// 10s
            // refresh
        };

        //根据已保存的判断是否已经选择答案
        var getcolors = function () {
            $http.post("./getColors").success(function (data) {
                for (var i = 0; i < data.length; i++) {
                    $("#box" + data[i]).css({"background": "#5eb95e"});
                }
            });
        };

        $(document).ready(function () {//当页面全部加载完调用
            getcolors();
        });

        var init = function () {
            basicinfo.getmyinfo().then(function (data) {
                $scope.realname = data.realname;
                $scope.userbh = data.userbh;
            });
            $scope.items = [];
            getmytestinfo().then(getmytest).then(function () {
                calcTime();
            }, function () {
                alert("获取考试信息失败");
            });
        };
        init();
    }]);

// 考试-展示（全部）
app.controller("test-full", [
    "$scope",
    "$http",
    "basicinfo",
    "$q",
    "dialog",
    function ($scope, $http, basicinfo, $q, dialog) {
        $scope.items = [];

        var getmytestinfo = function () {
            var def = $q.defer();
            $http.get("./getmytestinfo").success(function (data) {
                $scope.cnt = data.cnt;
                $scope.modelname = data.modelname;
                $scope.starttime = data.starttime;
                $scope.minutes = data.minutes;
                $scope.testbh = data.testbh;
                def.resolve();
            }).error(function () {
                def.reject("获取考试信息失败");
            });
            return def.promise;
        };

        var gettest = function () {
            var def = $q.defer();
            $http.get(
                "./mgr/gettestoptions?testbh="
                + encodeURI($scope.testbh)).success(
                function (data) {
                    var currentTest = {};
                    for (var i = 0, j = data.length; i < j; i++) {
                        var d = data[i];
                        var t = d.itemcontent;
                        if (currentTest.itemcontent != t) {
                            if (i != 0) {
                                $scope.items.push(currentTest);
                            }
                            currentTest = {};
                            currentTest.itemcontent = t;
                        }
                        currentTest.itemtype = d.itemtype;
                        currentTest.itembh = d.itembh;
                        currentTest.score = d.score;
                        var opts = currentTest.opts;
                        if (!opts) {
                            opts = [];
                            currentTest.opts = opts;
                        }
                        var opt = {};
                        opt.optno = d.optno;
                        opt.optbh = d.optbh;
                        opt.optcontent = d.optcontent;
                        opts.push(opt);
                    }
                    $scope.items.push(currentTest);
                    def.resolve();
                }).error(function () {
                def.reject("获取考试模板失败");
            });
            return def.promise;
        };

        var init = function () {
            basicinfo.getmyinfo().then(function (data) {
                $scope.realname = data.realname;
                $scope.userbh = data.userbh;
            });
            getmytestinfo().then(gettest).then(function () {
            }, function () {
                alert("获取考试信息失败");
            });
        };
        init();
    }]);

// 阅卷入口导航
app.controller("marking-nav", [
    "$scope",
    "$http",
    "basicinfo",
    function ($scope, $http, basicinfo) {
        $scope.items = [];
        var url = location.href;
        $scope.showmain = true;
        var p = /modelbh=(.*?)&userbh=(.*)/.exec(url);

        var init = function () {
            basicinfo.getmyinfo().then(function (data) {
                $scope.realname = data.realname;
                $scope.userbh = data.userbh;
            });
            $http.get("./getmytests").success(function (data) {
                var items = [];
                for (var i = 0, j = data.length; i < j; i++) {
                    var d = data[i];
                    if (!d.enabled) {
                        items.push(d);
                    }
                }
                $scope.items = items;
            }).error(function () {
                alert("获取试卷信息失败");
            });
        };
        init();

        $scope.go2marking = function (item) {
            $http.get("./getscorelist?modelbh=" + encodeURI(item.modelbh))
                .success(function (data) {
                    $scope.details = data;
                    $scope.modelname = data[0].modelname;
                    $scope.showmain = false;
                }).error(function () {
                alert("获取成绩失败");
            });
        };

        $scope.tomarking = function (item) {
            location.href = "./scoredetail?modelbh="
                + encodeURI(item.resourcebh) + "&userbh="

                + encodeURI(item.userbh);

            +encodeURI(item.userbh);

        };

        $scope.goback = function () {
            $scope.showmain = true;
        }

        if (p) {
            modelbh = p[1];
            userbh = p[2];
            var item = {
                "modelbh": modelbh
            };
            $scope.go2marking(item);
        }
    }]);

// 查询所有成绩
app.controller("admin-search", [
    "$scope",
    "$http",
    "$q",
    "basicinfo",
    "dialog",
    function ($scope, $http, $q, basicinfo, dialog) {
        var url = location.href;
        var typeint = 3;
        if (url.indexOf("yjauth") >= 0) {
            typeint = 2;
        }
        $scope.currentItem = {};
        $scope.authopt = false;
        $scope.data = toporganize;

        $scope.sexs = personsexs;

        $scope.checkall = false;
        $scope.orgs = [];
        $scope.orgPathMaps = [];

        var d = new Date().getYear() + 1900;
        $scope.nds = [];
        $scope.currentDetails = [];
        $scope.types = testitemtype;
        for (var i = d; i > d - 10; i--) {
            $scope.nds.push(i);
        }

        var snapshot = {};

        $scope.exportMarking = function () {
            var url = "./exportMarking?modelbh="
                + $scope.currentItem.modelbh;
            if ($scope.currentOrg.ext) {
                url += "&orgbh=" + encodeURI($scope.currentOrg.ext);
            }
            window.location = url;
        }

        $scope.edit = function (item) {
            $scope.currentItem = item;
            $scope.authopt = true;
        };

        $scope.search = function () {
            var url = "./getplans?t=t";
            if ($scope.qnd) {
                url += "&nd=" + $scope.qnd;
            }
            if ($scope.qseq) {
                url += "&seqbh=" + $scope.qseq;
            }
            if ($scope.qcate) {
                url += "&catebh=" + $scope.qcate;
            }
            $http.get(url).success(function (data) {
                $scope.items = data;
            }).error(function () {
                alert("获取计划失败");
            });
        };

        treeSelectedEvent("firstTree", function (event, data) {
            if (data.target) {
                var attr = data.target.ext || "--";
                $scope.currentOrg = snapshot[attr];
                var url = "./getmarkinglist?modelbh="
                    + $scope.currentItem.modelbh;
                if (attr != "--") {
                    url += "&orgbh=" + encodeURI(attr);
                }
                $http.get(url).success(function (data) {
                    $scope.persons = data;
                }).error(function () {
                    alert("获取成绩数据失败");
                });
            }
        });

        var buildTreeData = function (data, currentNode, orgtitle) {
            var attr = currentNode.ext;
            if (!orgtitle) {
                currentNode.path = currentNode.title;
            } else {
                currentNode.path = orgtitle + "/" + currentNode.title;
            }
            $scope.orgs.push(currentNode);
            $scope.orgPathMaps[attr] = currentNode.path;
            snapshot[attr || "--"] = currentNode;
            if (attr == "") { // root
                for (var i = 0, j = data.length; i < j; i++) {
                    var item = data[i];
                    var a = item.parentbh;
                    if (!a) {
                        var arr = currentNode.subs;
                        if (!arr) {
                            arr = [];
                            currentNode.subs = arr;
                        }
                        var a = {};
                        a.title = item.orgname;
                        a.ext = item.orgbh;
                        a.type = "item";
                        arr.push(a);
                        buildTreeData(data, a, currentNode.path);
                    }
                }
            } else {
                for (var i = 0, j = data.length; i < j; i++) {
                    var item = data[i];
                    var a = item.parentbh;
                    if (a == currentNode.ext) {
                        var arr = currentNode.subs;
                        if (!arr) {
                            arr = [];
                            currentNode.subs = arr;
                        }
                        var a = {};
                        a.title = item.orgname;
                        a.ext = item.orgbh;
                        a.type = "item";
                        arr.push(a);
                        buildTreeData(data, a, currentNode.path);
                    }
                }
            }
            if (currentNode.subs && currentNode.subs.length > 0) {
                currentNode.type = "folder";
            } else {
                currentNode.type = "item";
            }
        };

        var buildTree = function () {
            $('#firstTree').tree({
                dataSource: function (options, callback) {
                    try {
                        callback({
                            data: options.subs || $scope.data
                        });
                    } catch (e) {

                    }
                },
                multiSelect: false,
                cacheItems: false,
                folderSelect: true
            }).tree('discloseAll');
        };

        var getorganizes = function () {
            var def = $q.defer();
            basicinfo.getorgs().then(function (data) {
                buildTreeData(data, $scope.data[0]);
                buildTree();
                def.resolve();
            }, function () {
                def.reject("请求机构列表数据错误");
            });
            return def.promise;
        };

        var getlevels = function () {
            var def = $q.defer();
            basicinfo.getlevels().then(function (data) {
                $scope.levels = data;
                def.resolve();
            }, function () {
                def.reject("请求职级列表数据错误");
            });
            return def.promise;
        };

        var getcates = function () {
            var def = $q.defer();
            basicinfo.getcates().then(function (data) {
                $scope.cates = data;
                def.resolve();
            }, function () {
                def.reject("请分类列表数据错误");
            });
            return def.promise;
        };

        var getseqs = function () {
            var def = $q.defer();
            basicinfo.getseqs().then(function (data) {
                $scope.seqs = data;
                def.resolve();
            }, function () {
                def.reject("请序列列表数据错误");
            });
            return def.promise;
        };

        $scope.zjrd = function (item) {
            location.href = "./zjrd?modelbh="
                + encodeURI($scope.currentItem.modelbh) + "&username="
                + encodeURI(item.username);
        };

        var init = function () {
            getseqs().then(getcates).then(getlevels).then(getorganizes);
        };

        init();
    }]);

// 阅卷
app
    .controller(
        "marking",
        [
            "$scope",
            "$http",
            "basicinfo",
            "dialog",
            "$q",
            function ($scope, $http, basicinfo, dialog, $q) {
                $scope.items = [];
                var url = location.href, modelbh, userbh;
                var p = /modelbh=(.*?)&userbh=(.*)/.exec(url);
                if (p) {
                    modelbh = p[1];
                    userbh = p[2];
                }
                $scope.score_kg = 0;

                var postscoredetail = function () {
                    var def = $q.defer();
                    var items = [];
                    for (var i = 0, j = $scope.items.length; i < j; i++) {
                        var item = $scope.items[i];
                        var a = {};
                        a.testoptbh = item.testoptbh;
                        a.ext = "" + item.score2;
                        items.push(a);
                    }
                    $http.post("./postscoredetail", items).success(
                        function (data) {
                            if (data.status == "ok")
                                def.resolve();
                            else
                                def.reject();
                        }).error(function () {
                        def.reject();
                    });
                    return def.promise;
                };

                var init = function () {
                    basicinfo.getmyinfo().then(function (data) {
                        $scope.realname = data.realname;
                        $scope.userbh = data.userbh;
                    });
                    $http
                        .get(
                            "./getscorelist?modelbh="
                            + encodeURI(modelbh)
                            + "&userbh="
                            + encodeURI(userbh))
                        .success(
                            function (data) {
                                $scope.modelname = data[0].modelname;
                                $scope.score_kg = data[0].score1
                                    + data[0].score2;
                            }).error(function () {
                        alert("获取成绩失败");
                    });
                    $http
                        .get(
                            "./getcustmarkings?modelbh="
                            + encodeURI(modelbh)
                            + "&userbh="
                            + encodeURI(userbh))
                        .success(
                            function (data) {
                                if (data.length == 0) {
                                    dialog
                                        .alert("没有找到主观题！");
                                } else {
                                    $scope.items = data;
                                    for (var i = 0, j = $scope.items.length; i < j; i++) {
                                        var d = $scope.items[i];
                                        d.score2 = parseInt(d.ext || 0);
                                    }
                                }
                            }).error(function () {
                        alert("获取阅卷信息失败");
                    });
                };

                $scope.postcustscore = function () {
                    var totalscore = 0;
                    for (var i = 0, j = $scope.items.length; i < j; i++) {
                        var item = $scope.items[i];
                        var t = parseInt(item.score2 || 0);
                        if (t > item.score) {
                            dialog.alert("评分出现逻辑错误，给出的分数大于规定的分值 ["
                                + (i + 1) + "]");
                            return;
                        }
                        totalscore += t;
                    }

                    postscoredetail()
                        .then(
                            function () {
                                $http
                                    .get(
                                        "./postcustscore?modelbh="
                                        + encodeURI(modelbh)
                                        + "&userbh="
                                        + encodeURI(userbh)
                                        + "&score="
                                        + totalscore)
                                    .success(
                                        function (
                                            data) {
                                            if (data.status == "ok") {
                                                dialog
                                                    .confirm(
                                                        "分数保存成功，阅卷完毕，是否返回到成绩页面？",
                                                        function () {
                                                            location.href = "./index?modelbh="
                                                                + encodeURI(modelbh)
                                                                + "&userbh="
                                                                + encodeURI(userbh);
                                                        });
                                            } else {
                                                dialog
                                                    .alert(data.msg);
                                            }
                                        })
                                    .error(
                                        function () {
                                            alert("保存分数出错");
                                        });
                            });
                };

                $scope.goback = function () {
                    location.href = "./index?modelbh="
                        + encodeURI(modelbh) + "&userbh="
                        + encodeURI(userbh);
                };

                init();
            }]);

// 文档管理
app.controller("admin-doc", [
    "$scope",
    "$http",
    "basicinfo",
    "$q",
    "dialog",
    function ($scope, $http, basicinfo, $q, dialog) {
        $scope.currentItem = {};
        $scope.edit = function (item) {
            $scope.currentItem = item;
            $("#doc-modal-1").modal('open');
        };

        $scope.add = function () {
            $scope.currentItem = {};
            $("#doc-modal-1").modal('open');
        };

        $scope.deleteItem = function (item) {
            dialog.confirm("您真的要删除该文档吗？", function () {
                $http.get("./docdelete?docbh=" + encodeURI(item.docbh))
                    .success(function () {
                        location.reload();
                    });
            });
        };

        $scope.postData = function () {
            if ($scope.currentItem.docname == "") {
                dialog.alert("文档标题不能为空");
                return;
            }
            dialog.confirm(
                "您真的要提交文档 " + $scope.currentItem.docname + " 吗?",
                function () {
                    $("#docadd").submit();
                });
        };

        var init = function () {
            $http.get("./getdownloaddocs").success(function (data) {
                $scope.items = data;
            });
        };

        init();
    }]);

app.controller("download-docs", ["$scope", "$http", "basicinfo", "$q",
    "dialog", function ($scope, $http, basicinfo, $q, dialog) {
        var init = function () {
            $http.get("./getdownloaddocs").success(function (data) {
                var items = [];
                for (var i = 0, j = data.length; i < j; i++) {
                    var d = data[i];
                    var item = {};
                    item.docname = d.docname;
                    item.docbh = d.docbh;
                    item.createtime = d.createtime;
                    var ft = d.filetoken;
                    if (/upload(.*)/.test(ft)) {
                        item.href = "./upload" + RegExp.$1;
                    } else {
                        item.href = "";
                    }
                    items.push(item);
                }
                $scope.items = items;
            });
        };
        init();
    }]);

app.controller("test-score", [
    "$scope",
    "$http",
    "basicinfo",
    "$q",
    "dialog",
    function ($scope, $http, basicinfo, $q, dialog) {
        $scope.go2score = function (item) {
            // 直接展示分数的结果(只要客观题，成绩和分数不再需要认定)
            location.href = "./fenshu?modelbh=" + encodeURI(item.modelbh);
            return;
        };
        $scope.go2test = function (item) {
            // modelbh=" + encodeURI($scope.currentItem.modelbh) +
            // "&username=

            /*location.href = "./scorecard?modelbh="
						+ encodeURI(item.modelbh) + "&userbh="
						+ encodeURI(item.userbh);*/
            // 职级认定的结果展示
            $http.get("./scorecard?modelbh="
                + encodeURI(item.modelbh) + "&userbh="
                + encodeURI(item.userbh)).success(function (data) {
                if (data.status == "error") {
                    return alert("成绩正在审核中，请等待！");
                } else {
                    location.href = "./scorecard?modelbh="
                        + encodeURI(item.modelbh) + "&userbh="
                        + encodeURI(item.userbh);
                }
            });
        };

        $scope.tips = "";
        var init = function () {
            $http.get("./gettestscore").success(function (data) {
                $scope.items = data;
                if ($scope.items.length == 0) {
                    $scope.tips = "没有可以查询的成绩，如果刚完成考试，可能正在进行成绩认定工作，详情请咨询人力资源部";
                }
            });
        };

        init();
    }]);

app.controller("passorunpass", ["$scope", "$http", "basicinfo", "$q",
    "dialog", function ($scope, $http, basicinfo, $q, dialog) {
        var url = location.href;
        if (/\?(.*)/.test(url)) {
            params = RegExp.$1;
        }
        var init = function () {
            $http.get("./getscorecard?" + params).success(function (data) {
                $scope.item = data;
                var rq = data.rq;
                if (/(\d{4})-(\d{2})-(\d{2})/.test(rq)) {
                    $scope.item.n = RegExp.$1;
                    $scope.item.y = RegExp.$2;
                    $scope.item.r = RegExp.$3;
                }
            });
        };

        init();
    }]);

app.controller("scorecard", [
    "$scope",
    "$http",
    "basicinfo",
    "$q",
    "dialog",
    function ($scope, $http, basicinfo, $q, dialog) {
        $scope.levels = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2",
            "C3", "D1", "D2", "D3", "E1", "E2", "E3", "F1"];
        $scope.passorunpass = [{
            "label": "同意",
            "value": 1
        }, {
            "label": "不同意",
            "value": 0
        }];
        var url = location.href;
        var params = null;
        if (/zjrd\?(.*)/.test(url)) {
            params = RegExp.$1;
        }
        if (!params) {
            alert("参数错误");
            return;
        }
        $scope.item = {};
        var init = function () {
            $http.get("./gettestscore?" + params).success(function (data) {
                $scope.item = data;
            });
        };

        $scope.postData = function () {
            $http.post("./updatetestscore", $scope.item).success(
                function (data) {
                    if (data.status == "ok") {
                        alert("职级认定操作成功");
                    } else {
                        alert("更新失败");
                    }
                }).error(function () {
                alert("更新失败");
            });
        };

        init();

    }]);

app.controller("fenshu", [
    "$scope",
    "$http",
    function ($scope, $http) {
        // do nothing in this scope; hahaha
    }]);